<template>
  <!-- 增加修改 -->
  <a-drawer width="50%" :label-col="4" :wrapper-col="14" :visible="open" @close="onClose">
    <a-divider orientation="left">
      <b>{{ formTitle }}</b>
    </a-divider>
    <a-form-model ref="form" :model="form" :rules="rules" :layout="'horizontal'">
      <a-row :gutter="24">
        <a-col
          :span="24">
          <a-form-model-item label="指令单号" prop="orderNo">
            <a-input v-model="form.orderNo" placeholder="系统生成" disabled/>
          </a-form-model-item>
        </a-col>

      </a-row>
      <a-row :gutter="24">
        <a-col
          :span="12">
          <!-- externalBatchNumber -->
          <a-form-model-item label="零件名称" prop="partName">
            <a-tree-select
              v-model="form.partName"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="partList"
              placeholder="请选择"
              :replaceFields="{ children: 'children', title: 'showTitle', key: 'id', value: 'id' }"
              tree-default-expand-all
              @select="selectExternalBatchNumber"
            >
            </a-tree-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="来件状态" prop="incomingStatus">
            <a-radio-group :value="form.incomingStatus" v-model="form.incomingStatus" >
              <a-radio :value="0">
                已来件
              </a-radio>
              <a-radio :value="1">
                未来件
              </a-radio>

            </a-radio-group>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-model-item label="零件图号" prop="partDrawingNo">
            <a-input v-model="form.partDrawingNo" placeholder="请输入" disabled/>
          </a-form-model-item>
        </a-col>

        <a-col :span="12">
          <a-form-model-item label="内部批次号" prop="externalBatchNo" >
            <a-input v-model="form.externalBatchNo" placeholder="请输入" />
          </a-form-model-item>
        </a-col>
      </a-row>

      <a-row :gutter="24">
        <a-col
          :span="12">
          <a-form-model-item label="来件时间" prop="incomingTime">
            <!-- <a-input v-model="form.incomingTime" placeholder="请输入" :disabled="form.incomingStatus==0"/> -->
            <a-date-picker
              v-model="form.incomingTime"
              :disabled="form.incomingStatus==0"
              format="yyyy-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请输入"
              show-time/>
          </a-form-model-item>
        </a-col>
        <a-col
          :span="12">
          <a-form-model-item label="来件数量" prop="incomingQuantity">
            <a-input v-model="form.incomingQuantity" placeholder="请输入" :disabled="form.incomingStatus==0"/>

          </a-form-model-item>
        </a-col>

      </a-row>
      <a-row :gutter="24">
        <a-col
          :span="12">
          <a-form-model-item label="下发时间" prop="formalQuantity">
            <a-input v-model="form.formalQuantity" disabled placeholder="请输入"/>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="签发人" prop="testQuantity">
            <a-input v-model="form.testQuantity" disabled placeholder="请输入"/>
          </a-form-model-item>
        </a-col>
      </a-row>

      <a-row :gutter="24">
        <a-col
          :span="24">
          <a-form-model-item label="加工内容" prop="remark">
            <a-input type="textarea" v-model="form.remark" placeholder="请输入" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-divider />
      <!-- 交付节点 -->
      <a-row :gutter="24" class="action-bar">
        <a-space>
          <span>交付节点</span>
          <a-button type="primary" class="editable-add-btn" @click="addOrderNodeList">
            新增
          </a-button>
        </a-space>
      </a-row>

      <a-row :gutter="24">
        <a-table bordered :data-source="form.orderNodeList" :columns="orderNodeListColumns" size="small" :pagination="false">
          <!-- 序号列插槽 -->
          <template slot="indexSlot" slot-scope="text, record, index">
            {{ index + 1 }}
          </template>

          <template slot="processingQuantity" slot-scope="text, record">
            <a-input :value="text" @change="e=>handleChange(e.target.value, record, 'processingQuantity')"/>
          </template>

          <template slot="deliveryTime" slot-scope="text, record">
            <a-date-picker
              :value="text"
              :format="'YYYY-MM-DD HH:mm:ss'"
              :value-format="'YYYY-MM-DD HH:mm:ss'"
              :show-time="{ defaultValue: dayjs('00:00:00', 'HH:mm:ss') }"
              @change="e=>handleChange(e, record, 'deliveryTime')"
            />
          </template>

          <!-- :show-time="{ defaultValue: dayjs('00:00:00', 'HH:mm:ss') }" -->
          <template slot="action" slot-scope="text, record">
            <a href="javascript:;" @click="handleDelete(record)" >删除</a>
          </template>
        </a-table>

      </a-row>

      <!-- 加工设备 -->
      <a-row :gutter="24" class="action-bar">
        <a-space>
          <span class="action-bar-ttl">加工设备</span>
          <a-button type="primary" class="editable-add-btn" @click="addOrderEquipmentList">
            新增
          </a-button>
        </a-space>

      </a-row>

      <a-row :gutter="24">
        <a-table bordered :data-source="form.orderEquipmentList" :columns="orderEquipmentListColumns" size="small" :pagination="false">
          <!-- 序号列插槽 -->
          <template slot="indexSlot" slot-scope="text, record, index">
            {{ index + 1 }}
          </template>

          <template slot="equipmentName" slot-scope="text, record">
            <!-- <a-input :value="text" @change="e=>handleChange(e.target.value, record, 'equipmentName')"/> -->
            <a-select
              show-search
              placeholder="请选择"
              :value="text"
              @change="e=>handleEquipmenChange(e, record, 'equipmentName')"
            >
              <a-select-option :value="item.id" v-for="(item) in equipmentList" :key="item.id">
                {{ item.equipmentName }}
              </a-select-option>
            </a-select>

          </template>

          <template slot="equipmentModel" slot-scope="text, record">
            <a-select
              show-search
              placeholder="请选择"
              :value="text"
              @change="e=>handleChange(e, record, 'equipmentModel')"
            >
              <a-select-option :value="item" v-for="(item, key) in record.node.equipmentModel.replaceAll('；', ';').split(';') " :key="key">
                {{ item }}
              </a-select-option>
            </a-select>
          </template>

          <template slot="equipmentCode" slot-scope="text, record">
            <a-select
              show-search
              placeholder="请选择"
              :value="text"
              mode="multiple"
              @change="e=>handleChange(e, record, 'equipmentCode')"
            >
              <a-select-option :value="item" v-for="(item, key) in record.node.equipmentCode.replaceAll('；', ';').split(';') " :key="key">
                {{ item }}
              </a-select-option>
            </a-select>
          </template>

          <template slot="staffId" slot-scope="text, record">
            <!-- <a-input :value="text" @change="e=>handleChange(e.target.value, record, 'staffId')"/> -->
            <a-select
              show-search
              placeholder="请选择"
              :value="text"
              mode="multiple"
              @change="e=>handleChange(e, record, 'staffId')"
            >
              <a-select-option :value="item.id" v-for="(item, key) in opeUsers " :key="key">
                {{ item.nickName }}
              </a-select-option>
            </a-select>
          </template>

          <!-- :show-time="{ defaultValue: dayjs('00:00:00', 'HH:mm:ss') }" -->
          <template slot="action" slot-scope="text, record">
            <a href="javascript:;" @click="handleDeleteEquipment(record)" >删除</a>
          </template>
        </a-table>

      </a-row>

      <div class="bottom-control">
        <a-space>
          <a-button type="primary" :loading="submitLoading" @click="submitForm">
            保存
          </a-button>
          <a-button type="dashed" @click="cancel">
            取消
          </a-button>
        </a-space>
      </div>
    </a-form-model>
  </a-drawer>
</template>

<script>

import { listAll } from '@/api/system/user'
import { partPlanIncomingPage } from '@/api/plan/incoming'
import { list as warehouseReceiptList } from '@/api/materials/warehousing'
import { list } from '@/api/project/registration'
import { inventoryItem } from '@/api/baseData/inventory'
import { equipmentList } from '@/api/baseData/device'
import dayjs from 'dayjs'
import customParseFormat from 'dayjs/plugin/customParseFormat'
import { addProductionOrder, getById, updateProductionOrder } from '@/api/production/order'

export default {
  name: 'CreateForm',
  props: {
    deptOptions: {
      type: Array,
      required: true
    }
  },
  components: {
  },
  data () {
    dayjs.extend(customParseFormat)

    return {
      submitLoading: false,
      replaceFields: { children: 'children', title: 'partName', key: 'id', value: 'partName' },
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      formTitle: '',
      // 表单参数
      form: {
        orderNo: undefined,
        incomingStatus: undefined,
        partName: undefined,
        productionBatchNo: undefined,
        incomingQuantity: undefined,
        partDrawingNo: undefined,
        incomingTime: undefined,
        externalBatchNo: undefined,
        orderNodeList: [],
        orderEquipmentList: []
      },
      open: false,
      rules: {
        partName: [
          { required: true, message: '零件名称不能为空', trigger: 'change' }
        ],
        internalBatchNumber: [
          { required: true, message: '批次号不能为空', trigger: 'change' }
        ]
      },
      orderNodeListColumns: [
      {
        title: '序号',
        key: 'index',
        scopedSlots: { customRender: 'indexSlot' }, // 索引从0开始，+1后从1显示
        width: 80,
        align: 'center'
      },
        {
          title: '加工数量',
          dataIndex: 'processingQuantity',
          ellipsis: true,
          scopedSlots: { customRender: 'processingQuantity' },
          width: 80
        },
        {
          title: '交付节点',
          dataIndex: 'deliveryTime',
          scopedSlots: { customRender: 'deliveryTime' },
          ellipsis: true,
          width: 80
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          width: 50
        }

      ],
      orderEquipmentListColumns: [
      {
          title: '序号',
          key: 'index',
          scopedSlots: { customRender: 'indexSlot' }, // 索引从0开始，+1后从1显示
          width: 80,
          align: 'center'
        },
        {
          title: '设备名称',
          dataIndex: 'equipmentName',
          scopedSlots: { customRender: 'equipmentName' },
          ellipsis: true,
          width: 100
        },
        {
          title: '设备型号',
          dataIndex: 'equipmentModel',
          ellipsis: true,
          scopedSlots: { customRender: 'equipmentModel' },
          width: 100
        },
        {
          title: '可选设备',
          dataIndex: 'equipmentCode',
          scopedSlots: { customRender: 'equipmentCode' },
          ellipsis: true,
          width: 100
        },
        {
          title: '可选人员',
          dataIndex: 'staffId',
          scopedSlots: { customRender: 'staffId' },
          ellipsis: true,
          width: 100
        },
        {
          title: '操作',
          key: 'action',
          // fixed: 'right',
          width: 50,
          scopedSlots: { customRender: 'action' }
        }
      ],
      partList: [],
      inventoryItemList: [],
      nametestPieceEnum: [
        { label: '是', value: 1 },
        { label: '否', value: 0 }
      ],
      equipmentList: [],
      opeUsers: []
    }
  },
  filters: {
  },
  created () {
    // this.getPartPlanIncomingList()
    this.getinventoryItem()
    this.queryEquipmentList()
    this.getOperator()
  },
  computed: {
    // 处理后的数据，拼接 name 和 code
    processedTreeData () {
      const processData = (data) => {
        return this.inventoryItemList.map(item => ({
          title: `(${item.inventoryCode}|${item.inventoryName})`, // 拼接两个字段
          value: item.inventoryName,
          key: item.id,
          children: item.children ? processData(item.children) : undefined
        }))
      }
      return processData(this.rawTreeData)
    }

  },
  watch: {
    'form.incomingStatus': {
      handler (newItems) {
        if (newItems === 0) {
          // 已来 1、选择“已来件”时；指令单号=外部批次号/内部批次号，此时内部批次号由采购在毛坯到货时确定，零件名称从毛坯入库中选择，其余均为带入。
          this.warehouseReceiptList()
        } else if (newItems === 1) {
          // 未来 2、选择“未来件”时，选择外部批次号从来料交付计划中选择，此时生产批次号由生产人员指定，指令单号在生产人员指定完生产批次号后，同样=外部批次号/生产批次号。
          this.registrationList()
        }
        console.info(newItems, 'redio value')
      },
      deep: true // 深度监听
    },
    'form.orderNodeList': {
      handler (newItems) {
        console.log('数组内对象属性变化', newItems)
        var testNum = 0
        var num = 0
        newItems.forEach((element, index) => {
          if (element.nametestPiece === 1) {
            element.internalNumber = 'S' + ++testNum
          } else {
            element.internalNumber = 'Z' + ++num
          }
        })

        this.form.formalQuantity = num
        this.form.testQuantity = testNum
        this.form.totalQuantity = (num + testNum)
      },
      deep: true // 深度监听
    },
    'form.orderEquipmentList': {
      handler (newItems) {
        console.log('orderEquipmentList数组内对象属性变化', newItems)
      },
      deep: true // 深度监听
    }
  },
  methods: {
    dayjs, // 将 dayjs 作为方法暴露给模板
    getOperator () {
      listAll().then(res => {
        this.opeUsers = res.data
        console.info(res, '员工')
      })
    },
    // 设备库列表
    queryEquipmentList () {
      equipmentList({}).then(res => {
        this.equipmentList = res.data
      })
    },
    // 外来资料登记
    registrationList () {
      list({ progectId: this.selectProjectId }).then(res => {
        const s = res.data.map(item => {
          return { ...item, showTitle: item.partName + '|' + item.partDrawingNo }
        })
        this.partList = s
      })
    },
    // 毛坯入库
    warehouseReceiptList () {
      warehouseReceiptList({ progectId: this.selectProjectId }).then(res => {
        const s = res.data.map(item => { return { ...item, showTitle: item.partName + '|' + item.internalBatchNumber } })
        this.partList = s
      })
    },
    addOrderNodeList () {
      this.form.orderNodeList.push({
        deliveryTime: undefined,
        processingQuantity: undefined
      })
    },
    addOrderEquipmentList () {
      this.form.orderEquipmentList.push({
        id: new Date().getTime(),
        equipmentModel: undefined,
        equipmentName: undefined,
        equipmentCode: undefined,
        staffId: undefined,
        node: {
          equipmentModel: '',
          equipmentName: '',
          equipmentCode: '',
          staffId: undefined
        }
      })
    },
    handleDelete (record) {
      this.form.orderNodeList = this.form.orderNodeList.filter(item => item.internalNumber !== record.internalNumber)
    },
    handleDeleteEquipment (record) {
      this.form.orderEquipmentList = this.form.orderEquipmentList.filter(item => item.id !== record.id)
    },
    handleChange (e, info, ee) {
      console.info(e, info, ee)
      // info[ee] = e
      this.$set(info, ee, e)
    },
    handleEquipmenChange (e, info, ee) {
      // info[ee] = e
      console.info(e, info, ee, this.equipmentList, 'handleEquipmenChange')
      const node = this.equipmentList.filter(item => item.id === e)[0]
      console.info(node, 'node')
      // info[ee] = node.equipmentName
      // info['node'] = node
      this.$set(info, ee, node.equipmentName)
      this.$set(info, 'node', node)
    },
    // 选择外部批次号
    selectExternalBatchNumber (selectedKeys, info) {
      console.info(selectedKeys, info, '444')
      if (this.form.incomingStatus === 0) {
        // 已来件
        const node = this.partList.filter(it => it.id === selectedKeys)[0]
        console.info((this.partList.filter(it => it.id === selectedKeys)[0]))
        this.$set(this.form, 'partDrawingNo', node.partDrawingNo)
        this.$set(this.form, 'internalBatchNumber', node.internalBatchNumber)
        this.$set(this.form, 'partName', node.partName)
        this.$set(this.form, 'createTime', node.createTime)
        this.$set(this.form, 'incomingQuantity', node.incomingQuantity)
      } else {
//      未来件
        const node = this.partList.filter(it => it.id === selectedKeys)[0]
        console.info((this.partList.filter(it => it.id === selectedKeys)[0]))
        this.$set(this.form, 'partDrawingNo', node.partDrawingNo)
        // this.form.internalBatchNumber = node.internalBatchNumber
        this.$set(this.form, 'partName', node.partName)
        // this.form.incomingTime = node.createTime
        // this.form.incomingQuantity = node.totalQuantity
      }
    },
    // 选择零件名称
    selectPartName (selectedKeys, info) {
      console.log('selected', selectedKeys, info, this.inventoryItemList.filter(it => it.inventoryName === selectedKeys)[0])
      this.form.partAbbreviation = (this.inventoryItemList.filter(it => it.inventoryName === selectedKeys)[0]).shortName
      this.form.unitOfMeasurement = (this.inventoryItemList.filter(it => it.inventoryName === selectedKeys)[0]).unitOfMeasurement
    },
    // 来料交付计划列表
    getPartPlanIncomingList () {
      partPlanIncomingPage({ pageSize: 100, pageNum: 1 }).then(res => {
        this.partList = res.rows
      })
    },
    // 存货档案
    getinventoryItem () {
      inventoryItem().then(res => {
        this.inventoryItemList = res.rows
      })
    },
    onClose () {
      this.open = false
    },
    // 取消按钮
    cancel () {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset () {
      this.form = {
        receiptNumber: undefined,
        batchNumber: undefined,
        quantity: undefined,
        projectName: undefined,
        planArrivalDate: undefined,
        partDrawingNo: undefined,
        partName: undefined,
        remark: undefined,
        orderNodeList: []
      }
    },
    // 添加零件
    orderNodeList () {
      this.form.orderNodeList.push({
          nametestPiece: 0,
          partNumber: '',
          internalNumber: '',
          castingNumber: '',
          partName: this.form.partName

      })
    },
     /** 新增按钮操作 */
    handleAdd (selectProjectId) {
      if (!selectProjectId) {
        this.$message.error(
                '请先选择项目',
                3
              )
        return
      }
      this.reset()
      this.$emit('select-tree')
      this.open = true
      this.formTitle = '生产指令单'
      this.selectProjectId = selectProjectId
      this.form = {
       orderNo: undefined,
        incomingStatus: 0,
        partName: undefined,
        productionBatchNo: undefined,
        incomingQuantity: undefined,
        partDrawingNo: undefined,
        incomingTime: undefined,
        externalBatchNo: undefined,
        orderNodeList: [],
        orderEquipmentList: [],
        projectId: selectProjectId
      }
      this.warehouseReceiptList()
    },
    /** 修改按钮操作 */
    handleUpdate (row, ids) {
      this.reset()
      this.$emit('select-tree')
      this.formTitle = '修改生产指令单'
      getById(row.id).then(res => {
        this.form = res.data
        if (!this.form.orderNodeList) {
          this.form.orderNodeList = []
        }
        this.open = true
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      console.info(this.form, '3333')
      this.$refs.form.validate(valid => {
        if (valid) {
          this.submitLoading = true
          if (this.form.id !== undefined) {
            updateProductionOrder(this.form).then(response => {
              this.$message.success(
                '修改成功',
                3
              )
              this.open = false
              this.$emit('ok')
            }).finally(() => {
              this.submitLoading = false
            })
          } else {
            addProductionOrder(this.form).then(response => {
              this.$message.success(
                '新增成功',
                3
              )
              this.open = false
              this.$emit('ok')
            }).finally(() => {
              this.submitLoading = false
            })
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>

</style>
